package com.example.cardgame

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.ImageView
import android.widget.RadioGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

class InfoActivity : AppCompatActivity() {
    private lateinit var profileImageView: ImageView
    private lateinit var nameEditText: EditText
    private lateinit var studentIdEditText: EditText
    private lateinit var phoneEditText: EditText
    private lateinit var emailEditText: EditText
    private lateinit var genderRadioGroup: RadioGroup
    private lateinit var travelCheckBox: CheckBox
    private lateinit var readingCheckBox: CheckBox
    private lateinit var gamingCheckBox: CheckBox
    private lateinit var shoppingCheckBox: CheckBox
    private lateinit var saveButton: Button
    private lateinit var changeProfileButton: Button
    private var profileImageBitmap: Bitmap? = null

    companion object {
        private const val REQUEST_IMAGE_CAPTURE = 1
        private const val REQUEST_CAMERA_PERMISSION = 2
    }

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_info)
        title = getString(R.string.modify_personal_information)

        profileImageView = findViewById(R.id.profileImageView)
        changeProfileButton = findViewById(R.id.changeProfileButton)
        nameEditText = findViewById(R.id.nameEditText)
        studentIdEditText = findViewById(R.id.studentIdEditText)
        phoneEditText = findViewById(R.id.phoneEditText)
        emailEditText = findViewById(R.id.emailEditText)
        genderRadioGroup = findViewById(R.id.genderRadioGroup)
        travelCheckBox = findViewById(R.id.travelCheckBox)
        readingCheckBox = findViewById(R.id.readingCheckBox)
        gamingCheckBox = findViewById(R.id.gamingCheckBox)
        shoppingCheckBox = findViewById(R.id.shoppingCheckBox)
        saveButton = findViewById(R.id.saveButton)

        changeProfileButton.setOnClickListener {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), REQUEST_CAMERA_PERMISSION)
            } else {
                dispatchTakePictureIntent()
            }
        }

        val name = intent.getStringExtra("name") ?: ""
        val gender = intent.getStringExtra("gender") ?: ""
        val studentId = intent.getStringExtra("studentId") ?: ""
        val phone = intent.getStringExtra("phone") ?: ""
        val email = intent.getStringExtra("email") ?: ""
        val hobbies = intent.getStringExtra("hobbies") ?: ""

        nameEditText.setText(name)
        studentIdEditText.setText(studentId)
        phoneEditText.setText(phone)
        emailEditText.setText(email)

        if (gender == "男") {
            genderRadioGroup.check(R.id.maleRadioButton)
        } else if (gender == "女") {
            genderRadioGroup.check(R.id.femaleRadioButton)
        }

        travelCheckBox.isChecked = hobbies.contains("旅游")
        readingCheckBox.isChecked = hobbies.contains("阅读")
        gamingCheckBox.isChecked = hobbies.contains("游戏")
        shoppingCheckBox.isChecked = hobbies.contains("购物")

        saveButton.setOnClickListener {
            val selectedGender = when (genderRadioGroup.checkedRadioButtonId) {
                R.id.maleRadioButton -> "男"
                R.id.femaleRadioButton -> "女"
                else -> ""
            }

            val selectedHobbies = mutableListOf<String>()
            if (travelCheckBox.isChecked) selectedHobbies.add("旅游")
            if (readingCheckBox.isChecked) selectedHobbies.add("阅读")
            if (gamingCheckBox.isChecked) selectedHobbies.add("游戏")
            if (shoppingCheckBox.isChecked) selectedHobbies.add("购物")

            val intent = Intent()
            intent.putExtra("name", nameEditText.text.toString())
            intent.putExtra("gender", selectedGender)
            intent.putExtra("studentId", studentIdEditText.text.toString())
            intent.putExtra("phone", phoneEditText.text.toString())
            intent.putExtra("email", emailEditText.text.toString())
            intent.putExtra("hobbies", selectedHobbies.joinToString(","))
            profileImageBitmap?.let {
                intent.putExtra("profileImage", it)
            }
            setResult(RESULT_OK, intent)
            finish()
        }
    }

    private fun dispatchTakePictureIntent() {
        Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
            takePictureIntent.resolveActivity(packageManager)?.also {
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                dispatchTakePictureIntent()
            } else {
                // Permission denied, show a message to the user
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
            val imageBitmap = data?.extras?.get("data") as Bitmap
            profileImageBitmap = imageBitmap
            profileImageView.setImageBitmap(imageBitmap)
        }
    }
}